package com.aiwei.tdjk.controller;

import com.aiwei.tdjk.common.Constants;
import com.aiwei.tdjk.dto.request.DeliveryPagerRequest;
import com.aiwei.tdjk.entity.Delivery;
import com.aiwei.tdjk.entity.DeliveryDetail;
import com.aiwei.tdjk.entity.SaleOrderHeader;
import com.aiwei.tdjk.entity.SaleOrderItem;
import com.aiwei.tdjk.enums.DeliveryStatusEnum;
import com.aiwei.tdjk.enums.SaleOrderStatusEnum;
import com.aiwei.tdjk.service.DeliveryDetailService;
import com.aiwei.tdjk.service.DeliveryService;
import com.aiwei.tdjk.service.SaleOrderHeaderService;
import com.aiwei.tdjk.service.SaleOrderItemService;
import com.aiwei.tdjk.utils.SnUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;

/**
 * 内贸销售
 */
@Controller
@RequestMapping(value = "/admin/deliveryInner")
public class DeliveryInnerController extends BaseController {


	@Autowired
	private SaleOrderHeaderService saleOrderHeaderService;

	@Autowired
	private SaleOrderItemService saleOrderItemService;

	@Autowired
	private DeliveryService deliveryService;

	@Autowired
	private DeliveryDetailService deliveryDetailService;



	@RequestMapping(value = {"/list"}, method = RequestMethod.GET)
	public String list(DeliveryPagerRequest request, Model model) {
		request.setType(2);
		model.addAttribute("page", deliveryService.find(request));
		model.addAttribute("delivery", request);
		return viewName("list");
	}


	/**
	 * @param model
	 * @param ids   根据内销订单的id，发货单
	 * @return
	 */
	@RequestMapping(value = "create", method = RequestMethod.GET)
	public String showCreateForm(Model model, Long ids) {
		model.addAttribute(Constants.OP_NAME, "新增");
		Delivery delivery = new Delivery();
		model.addAttribute("m", delivery);


		SaleOrderHeader saleOrderHeader = saleOrderHeaderService.get(ids);
		List<SaleOrderItem> saleOrderItems = saleOrderItemService.getListByOrderCode(saleOrderHeader.getSaleordercode());

		model.addAttribute("saleOrderHeader", saleOrderHeader);
		model.addAttribute("saleOrderItems", saleOrderItems);

		//已经制定的发货单的数量、
		List<Delivery> listBySaleOrderCode = deliveryService.getListBySaleOrderCode(saleOrderHeader.getSaleordercode());
		int markedDeliverCount = 0;
		if (listBySaleOrderCode != null)
			markedDeliverCount = listBySaleOrderCode.size();
		model.addAttribute("markedDeliverCount", markedDeliverCount);
		//已经发货的订单项目数量
		model.addAttribute("hasNotDeliverCount", deliveryService.getHasNotDeliveryItemList(saleOrderHeader.getSaleordercode()));

		return viewName("editForm");
	}

	@RequestMapping(value = "create", method = RequestMethod.POST)
	public String create( Delivery delivery, String saleordercode, String[] saleorderitemcode, Integer[] packingQty, BindingResult result,
						 RedirectAttributes redirectAttributes) {
//		if (hasError(result))
//			return showCreateForm(model);


		//验证已经发送的订单项目，是否超过了 todo  前端验证
		HashMap<String, Integer> map = deliveryService.getHasNotDeliveryItemList(saleordercode);

		//保存发货单基本信息、发货单详情
		String sn = "FD" + SnUtils.generate();
		delivery.setDeliveryCode(sn);
		delivery.setSaleOrderCode(saleordercode);
		delivery.setType(2);
		deliveryService.add(delivery);

		//生成发货单详情
		for (int i = 0; i < saleorderitemcode.length; i++) {
			DeliveryDetail deliveryDetail = new DeliveryDetail();
			deliveryDetail.setDeliveryId(delivery.getId().toString());
			deliveryDetail.setSaleOrderItemCode(saleorderitemcode[i]);
			deliveryDetail.setDeliveryQty(packingQty[i]);
			deliveryDetail.setStandard(saleOrderItemService.getStandardBysSaleOrderItemCode(saleorderitemcode[i]));
			deliveryDetailService.add(deliveryDetail);
		}

		//修改订单的状态为已经订舱完成
		SaleOrderHeader saleOrderHeader = saleOrderHeaderService.getBySaleOrderCode(saleordercode);
		saleOrderHeader.setOrderstate(SaleOrderStatusEnum.booked.getCode().toString());
		saleOrderHeaderService.update(saleOrderHeader);

		redirectAttributes.addFlashAttribute(Constants.MESSAGE, "新增成功");
		return "redirect:"+"/admin/saleOrderHeader/listInner";
	}



	/**
	 * 查看发货单(内销)  仓库人员查看
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "{id}/update", method = RequestMethod.GET)
	public String showUpdateForm(@PathVariable("id") Long id, Model model) {
		model.addAttribute(Constants.OP_NAME, "修改");

		model.addAttribute("deliveryId", id);
		Delivery delivery = deliveryService.get(id);
		model.addAttribute("m", delivery);
		//发货详情
		List<DeliveryDetail> deliveryDetailList = deliveryDetailService.getListByDeliveryId(delivery.getId());
		model.addAttribute("deliveryDetailList", deliveryDetailList);
		//查询订单的情况
		SaleOrderHeader saleOrderHeader = saleOrderHeaderService.getBySaleOrderCode(delivery.getSaleOrderCode());
		model.addAttribute("saleOrderHeader", saleOrderHeader);

		return viewName("viewForm");

	}

	@RequestMapping(value = "changeStatus/{newStatus}")
	public String changeStatus(
			HttpServletRequest request,
			@RequestParam("ids") Long[] ids,
			@PathVariable("newStatus") DeliveryStatusEnum newStatus,
			RedirectAttributes redirectAttributes) {

		deliveryService.changeStatus(ids, newStatus);

		if (newStatus == DeliveryStatusEnum.lock) {
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, "锁定成功！");
		} else if (newStatus == DeliveryStatusEnum.unlock) {
			redirectAttributes.addFlashAttribute(Constants.MESSAGE, "解锁成功！");
		}
		return redirectToUrl("list");
	}



	/**
	 * 仓库人员确认  内销
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "{id}/confirm")
	public String confirm(@PathVariable("id") Long id,RedirectAttributes redirectAttributes) {
		//确认：修改发货单状态为"已报关"，修改商检相关,手册的使用状态为"已报关"
		Delivery delivery = deliveryService.get(id);
		// 判读发货单的状态是否为锁定状态
		if (delivery.getStatus()!= DeliveryStatusEnum.lock.getCode()){
			redirectAttributes.addFlashAttribute(Constants.ERROR, "请先锁定或者该发货单已经商检完成！");
			return redirectToUrl("list");
		}
		delivery.setStatus(DeliveryStatusEnum.innerConfirm.getCode());
		deliveryService.update(delivery);

		//订单修改为："确认"
		SaleOrderHeader saleOrderHeader = saleOrderHeaderService.getBySaleOrderCode(delivery.getSaleOrderCode());
		saleOrderHeader.setOrderstate(SaleOrderStatusEnum.confirmed.getCode().toString());
		saleOrderHeaderService.update(saleOrderHeader);

		return redirectToUrl("list");
	}

	/**
	 * 仓库人员撤回  内销
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "{id}/refuse")
	public String refuse(@PathVariable("id") Long id,RedirectAttributes redirectAttributes) {
		//撤回：修改发货单状态为"撤回"
		Delivery delivery = deliveryService.get(id);
		delivery.setStatus(DeliveryStatusEnum.refused.getCode());
		deliveryService.update(delivery);

        //订单修改为："仓库撤回"
        SaleOrderHeader saleOrderHeader = saleOrderHeaderService.getBySaleOrderCode(delivery.getSaleOrderCode());
        saleOrderHeader.setOrderstate(SaleOrderStatusEnum.refused.getCode().toString());
        saleOrderHeaderService.update(saleOrderHeader);

		// 删除发货单详情 参照跟单的  退会
		List<Delivery> deliveryList = deliveryService.getListBySaleOrderCode(delivery.getSaleOrderCode());
		deliveryDetailService.deleteListByDeliveryId(deliveryList);

		return redirectToUrl("list");
	}




}
